'use strict';

describe('table component', function () {

	beforeEach(module('lgTable'));

	describe('Talbe Controller', function () {
		var controller;
		var mockData;
		var mockResource;
		var mockTableParams = {
			columns:angular.noop,
			settings:function(){return {};},
			params:angular.noop
		};
		var mockRowForm = {$setPristine : angular.noop};

		function mockNgTableParams(params, settings){
			return {data:mockData, params:params, settings:settings};
		}

		beforeEach(inject(function ($controller) {
			mockData = [{id:1,no:1},{id:2,no:2},{id:3,no:3}];
			mockResource = function(){
			return {
				fetchAll : function(){
					return mockData;
				}
			};
		};
			controller = $controller('TableCtrl', {NgTableParams:mockNgTableParams,TableParams:mockTableParams, Resource:mockResource});
			controller.tableTracker = {untrack:function(row){console.log(row);}};
		}));

		it('should store columns', function () {
		  expect(controller.cols).toBe(mockTableParams.columns());
		});

		it('should store params and settings', function () {
		  expect(controller.tableParams.data).toBe(mockData);
		  expect(controller.tableParams.params).toBe(mockTableParams.params());
		  expect(controller.tableParams.settings.getData()).toBe(mockResource().fetchAll());
		});

		it('should add an item temporarily', function(){
			controller.add();
		    expect(controller.tableParams.data.length).toBe(4);
			var row = controller.tableParams.data.shift();
			expect(row.isEditing).toBe(true);
			expect(row.isAdding).toBe(true);
		});

		it('nothing should change if add but cancel later', function(){
			controller.add();
		    expect(controller.tableParams.data.length).toBe(4);
			var row = controller.tableParams.data[0];
			controller.cancel(row, mockRowForm);
		    expect(controller.tableParams.data.length).toBe(3);
		});

		it('one item should be added if add and save', function(){
			controller.add();
			var row = controller.tableParams.data[0];
			row.no = 8;
			controller.save(row, mockRowForm);
		    expect(controller.tableParams.data.length).toBe(4);
			row = controller.tableParams.data[0];
		    expect(row.no).toBe(8);
		});

		it('nothing should change if edit but cancel later', function(){
			var row = controller.tableParams.data[0];
			controller.edit(row);
			angular.extend(row, {no:8});
		    expect(row.no).toBe(8);
			controller.cancel(row, mockRowForm);
		    expect(row.no).toBe(1);
		});

		it('the item should be modified if edit and save', function(){
			var row = controller.tableParams.data[0];
			controller.edit(row);
			row.no = 8;
			controller.save(row, mockRowForm);
			row = controller.tableParams.data[0];
		    expect(row.no).toBe(8);
		});

	});

});
